package xin.alum.aim.model;

import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;
import lombok.SneakyThrows;

import java.io.IOException;
import java.util.List;

/**
 * JSON 序列化，若属性存在默认值则不输出
 * 如：code=0,message=“”
 */
public class ProtoUtil {

    private final JsonFormat.Printer printer;
    private final JsonFormat.Parser parser;

    public ProtoUtil() {
        printer = JsonFormat.printer();
        parser = JsonFormat.parser();
    }

    public ProtoUtil(Descriptors.Descriptor anyFieldDescriptor) {
        JsonFormat.TypeRegistry typeRegistry = JsonFormat.TypeRegistry.newBuilder().add(anyFieldDescriptor).build();
        printer = JsonFormat.printer().usingTypeRegistry(typeRegistry);
        parser = JsonFormat.parser().usingTypeRegistry(typeRegistry);
    }

    public ProtoUtil(List<Descriptors.Descriptor> anyFieldDescriptor) {
        JsonFormat.TypeRegistry typeRegistry = JsonFormat.TypeRegistry.newBuilder().add(anyFieldDescriptor).build();
        printer = JsonFormat.printer().usingTypeRegistry(typeRegistry);
        parser = JsonFormat.parser().usingTypeRegistry(typeRegistry);
    }

    /**
     * 返回纯净JSON串
     *
     * @param sourceMessage
     * @return
     * @throws IOException
     */
    public String toJson(MessageOrBuilder sourceMessage) throws IOException {
        return printer.print(sourceMessage).replace("\n", "").replace(" ", "");
    }

    @SneakyThrows
    public Message toProto(Message.Builder targetBuilder, String json) {
        parser.merge(json, targetBuilder);
        return targetBuilder.build();
    }
}
